import { createRouter, createWebHistory } from 'vue-router'
import store from '../store'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/Login.vue'),
      meta: { guest: true }
    },
    {
      path: '/',
      name: 'Layout',
      component: () => import('../views/Layout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: 'books',
          name: 'Books',
          component: () => import('../views/Books.vue')
        },
        {
          path: 'users',
          name: 'Users',
          component: () => import('../views/Users.vue'),
          meta: { requiresAdmin: true }
        },
        {
          path: 'borrowing',
          name: 'Borrowing',
          component: () => import('../views/Borrowing.vue')
        }
      ]
    }
  ]
})

router.beforeEach(async (to, from, next) => {
  const token = store.state.token
  const user = store.state.user

  if (to.meta.guest && token) {
    next('/')
    return
  }

  if (to.meta.requiresAuth && !token) {
    next('/login')
    return
  }

  if (to.meta.requiresAdmin && (!user || !user.roles.some(role => role.name === 'ROLE_ADMIN'))) {
    next('/')
    return
  }

  next()
})

export default router 